package com.bsj.travel.security.aspect;

import com.bsj.travel.constant.SecurityConstants;
import com.bsj.travel.def.global.JsonResultEnum;
import com.bsj.travel.exception.InnerAuthException;
import com.bsj.travel.security.annotation.InnerAuth;
import com.bsj.travel.util.ServletUtils;
import com.bsj.travel.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author yinhao
 * @version 1.0
 * @description 内部服务调用验证
 * @date 2023/11/1
 */
@Aspect
@Component
public class InnerAuthAspect implements Ordered {

    /**
     * 该权限认证需要在AOP前执行
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }

    /**
     * 接口上添加InnerAuth注解表示该接口为内部调用
     * @param point
     * @param innerAuth
     * @return
     * @throws Throwable
     */
    @Around("@annotation(innerAuth)")
    public Object innerAround(ProceedingJoinPoint point, InnerAuth innerAuth) throws Throwable {
        String source = ServletUtils.getRequest().getHeader(SecurityConstants.FROM_SOURCE);
        //内部请求认证
        if (!StringUtils.equals(SecurityConstants.INNER, source)) {
            throw new InnerAuthException(JsonResultEnum.NOT_INNER_AUTH);
        }
        String userId = ServletUtils.getRequest().getHeader(SecurityConstants.USER_ID);
        String userName = ServletUtils.getRequest().getHeader(SecurityConstants.USER_NAME);
        //用户信息认证
        if (innerAuth.isUser() && (StringUtils.isEmpty(userId) || StringUtils.isEmpty(userName))) {
            throw new InnerAuthException(JsonResultEnum.NOT_INNER_USER);
        }
        return point.proceed();
    }
}
